package cn.dc406.labc406mgr.controller;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


@RestController
public class ImgController {
    @CrossOrigin()
    @ResponseBody
    @RequestMapping("/upload")
    public String upload(MultipartFile picFile,String name) throws IOException {
        System.out.println("imgstart");
        //得到原始文件夹名
        String fileName =  name+".jpg";
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\img\\items\\";
        String end = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\target\\classes\\static\\img\\items\\";
        String path = pre +fileName;
        String path2=end+fileName;
        FileOutputStream os=new FileOutputStream(path2);
        System.out.println(path2);
        FileCopyUtils.copy(picFile.getInputStream(),os);
        picFile.transferTo(new File(path));
        return "img/items/"+fileName;
    }

//    @CrossOrigin()
//    @ResponseBody
//    @RequestMapping("/remove")
//    public void remove(String name){
//        System.out.println("remove");
//        String fileName =  name+".jpg";
//        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
//        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\img.items\\";
//        String end = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() + "\\target\\classes\\static\\img.items\\";
//        String path = pre +fileName;
//        String path2=end+fileName;
//        new File(path).delete();//删除文件
//        new File(path2).delete();//删除文件
//    }
}